package com.minivision.sdktestdemo.ui;


import android.content.Context;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewStub;
import android.widget.ImageView;

import com.minivision.sdktestdemo.R;
import com.minivision.sdktestdemo.bean.KeyBean;
import com.minivision.sdktestdemo.bean.MusicBean;
import com.minivision.sdktestdemo.controler.ui.list.DirPathListControler;
import com.minivision.sdktestdemo.controler.ui.list.ListControler;
import com.minivision.sdktestdemo.controler.ui.viewpager.MusicNavControler;
import com.minivision.sdktestdemo.event.DataModificationEvent;
import com.minivision.sdktestdemo.event.PlayMusicEvent;
import com.minivision.sdktestdemo.model.Provider;
import com.minivision.sdktestdemo.ui.view.GroupCtrlPopContentView;
import com.minivision.sdktestdemo.ui.view.PopupView;

import org.greenrobot.eventbus.EventBus;

import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link ClassfiedInfoFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class ClassfiedInfoFragment extends Fragment implements MusicItemRecyclerAdapter.OnItemListener,
        MusicItemRecyclerAdapter.onPlayEventChanged, OnFragmentUpdatedListener {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mTitle;
    private Class mClass;
    private OnFragmentInteractionListener mListener;


    public ClassfiedInfoFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment ClassfiedInfoFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static ClassfiedInfoFragment newInstance(String param1, Class<?> param2) {
        ClassfiedInfoFragment fragment = new ClassfiedInfoFragment();
        Bundle args = new Bundle();
        args.putString(MusicNavControler.PARAM1, param1);
        args.putSerializable(MusicNavControler.PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mTitle = getArguments().getString(MusicNavControler.PARAM1);
            mClass = (Class) getArguments().getSerializable(MusicNavControler.PARAM2);
        }
        mPopupView = new PopupView(getActivity(), new GroupCtrlPopContentView(getActivity()));
        mExecutor = Executors.newSingleThreadExecutor();
        Log.i("ClassfiedInfoFragment", "onCreate: ");
    }

    @Bind(R.id.music_list)
    RecyclerView mRecyclerView;

    private MusicItemRecyclerAdapter mAdapter;

    private ListControler mListControler;

    private String mKeyUri;

    private PopupView mPopupView;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_singer, container, false);
        ButterKnife.bind(this, view);
        initData();
        initView();
        return view;
    }

    private void initView() {
        mRecyclerView.setHasFixedSize(true);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        mRecyclerView.setAdapter(mAdapter);
        initProgress();
    }

    public void initProgress() {
        if (mAdapter.getItemCount() == 0) {
            mStubLoad.setVisibility(View.VISIBLE);
            ImageView imageView = (ImageView) mStubLoad.findViewById(R.id.img_anim);
            AnimationDrawable drawable = (AnimationDrawable) imageView.getDrawable();
            drawable.start();
        }
    }

    @Bind(R.id.loading)
    ViewGroup mStubLoad;

    private void initData() {
        try {
            mListControler = mListControler == null ?
                    (ListControler) mClass.getConstructor(Context.class).newInstance(getActivity()) : mListControler;
            mAdapter = mAdapter == null ? new MusicItemRecyclerAdapter(this, mListControler) : mAdapter;
            mAdapter.setItemClickListener(this);
        } catch (java.lang.InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDestroyView() {
        ButterKnife.unbind(this);
        Log.i("ClassfiedInfoFragment", "onStop: ");
        super.onDestroyView();
    }

    @Override
    public String getKeyUri() {
        return mKeyUri == null ? "" : mKeyUri;
    }

    @Override
    public int getType() {
        return MusicItemRecyclerAdapter.CLASSFIED_LIST;
    }

    @Override
    public void onItemClick(View v, int position) {
        Provider provider = mListControler.getmProvider();
        KeyBean keyBean = (KeyBean) provider.get(position);
        mListener.onClick(mListControler.getTitle(position), keyBean.getmListSongs());
    }

    @Override
    public void onMoreItemClick(int position) {
        KeyBean keyBean = (KeyBean) mListControler.getmProvider().get(position);
        mPopupView.show(keyBean, mListControler.getType());
    }

    @Override
    public void update(PlayMusicEvent event) {
        if (mListControler.notifyDataChanged()) {
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    ImageView imageView = (ImageView) mStubLoad.findViewById(R.id.img_anim);
                    AnimationDrawable drawable = (AnimationDrawable) imageView.getDrawable();
                    drawable.stop();
                    mStubLoad.setVisibility(View.GONE);
                    mAdapter.notifyDataSetChanged();
                }
            });
        }
        int pos = getClassfiedPos(event);
        if (pos != -1) {
            mKeyUri = mListControler.getTitle(pos);
            if (mListControler instanceof DirPathListControler) {
                mKeyUri = mListControler.getContent(pos) + mListControler.getTitle(pos);
            }
        }
    }

    @Override
    public void update(DataModificationEvent event) {
        switch (event.mAction) {
            case DataModificationEvent.ACTION_GROUP_PLAY:
                break;
            case DataModificationEvent.ACTION_CHANGE:
            case DataModificationEvent.ACTION_DELETE:
            case DataModificationEvent.ACTION_LIST_CLEAR:
                if (mListControler.notifyDataChanged()) {
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mAdapter.notifyDataSetChanged();
                        }
                    });
                }
                break;
        }
    }

    private PlayMusicEvent mEvent;

    private ExecutorService mExecutor;

    @Override
    public void setPlayEvent(PlayMusicEvent event) {
        if (mEvent == null) {
            mEvent = event;
        } else {
            mEvent.setPlayEvent(event);
        }
    }

    public int getClassfiedPos(PlayMusicEvent event) {
        if (event != null) {
            for (int i = 0; i < mListControler.size(); ++i) {
                Provider provider = mListControler.getmProvider();
                KeyBean bean = (KeyBean) provider.get(i);
                for (MusicBean item : bean.getmListSongs()) {
                    if (item.getmPath().equals(event.mUri)) {
                        return i;
                    }
                }
            }
        }
        return -1;
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (getUserVisibleHint()) {
            mExecutor.execute(new Runnable() {
                @Override
                public void run() {
                    update(mEvent);
                }
            });
        }
    }

    public interface OnFragmentInteractionListener {
        void onClick(String title, List<MusicBean> list);
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mExecutor.shutdownNow();
        mListener = null;
    }
}
